<template>
    <div :id="idName"></div>
</template>
<script>
import { Pie } from '@antv/g2plot';

export default {
  props: {
    transferPieData: Array,
    setting: Object
  },
  data () {
    return {
      piePlot: null,
      idName: '',
      total: 0
    };
  },
  watch: {
    //  this.piePlot.changeData(val); 只可以更改图表展示，但statistic里的 total未更新。
    //  因此使用下面卸载组件，重新render方法
    transferPieData (val) {
      this.piePlot.destroy();
      this.total = this.totalCount()  
      this.$nextTick(()=> {
        this.render();
      })
    }
  },
  created () {
    this.idName = 'pie-' + Math.random().toString(36).slice(-4); // 随机生成id
  },
  mounted () {
    this.total = this.totalCount()
    this.$nextTick(()=> {
      this.render();
    })
  },
  beforeDestroy(){
    this.piePlot.destroy();
  },
  methods: {
    totalCount () {
      const res = this.transferPieData.reduce((r, c) => r + c.value, 0);
      return res;
    },
    render () {
      const self = this;
      this.piePlot = new Pie(self.idName, {
        data: self.transferPieData,
        noData: { content: '暂无数据' },
        angleField: 'value',
        colorField: 'type',
        color: this.setting.color,
        height: 240,
        padding: [0, 0, 0, 0],
        radius: 0.6,
        innerRadius: 0.7,
        appendPadding: [-30, 0, 0, 0],
        legend: {
          position: 'bottom',
          offsetY:-10,
          marker: {
            symbol: 'square'
          },
          itemName: {
            style: {
              fill: '#1d2129'
            }
          }
        },
        statistic: {
          title: {
            style: {
              fontSize: 16,
              fill: '#606266',
              textAlign: 'center',
            },
            content: self.total,
            offsetY: -5,
          },
          content: {
            style: {
              fontSize: 12,
              fill: '#8c8c8c',
              textAlign: 'center',
            },
            content: this.setting.text,
            offsetY: 5,
          },
        },
        tooltip: {
          formatter: (datum) => {
            return { name: datum.type, value: Math.round(datum.value / self.total*100) + '%' };
          },
        }
     
      });
      this.piePlot.render();
    }
  }
};
</script>
<style lang="scss" scoped>

</style>
